﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using TCKQKL.FrontEnd.DataModel;
using LoanMonitor.Business;
using StockTrader.FrontEnd.DataContract;
using StockTrader.BusinessService.DataContract.Mortgate;
using Mortgage.DDL;
using Mortgage.DAL;
using Mortgage.Enum;

namespace LoanMonitor.Utils
{
    public partial class frmMortgage : Form
    {
        private List<InvestorDataUI> assignAcc = new List<InvestorDataUI>();
        private List<StocksUI> asset = new List<StocksUI>();
        private List<CollateralUI> collaterals = new List<CollateralUI>();
        private MortgageMornitorDAL client = new MortgageMornitorDAL();
        private DALclient history = new DALclient();
        private bool isContractReady = false;

        public frmMortgage()
        {
            InitializeComponent();
        }

        private void btnEvaluate_Click(object sender, EventArgs e)
        {
            CollateralUI col = new CollateralUI();
            decimal mortgateAmount = 0;
            List<StocksData> customerHolding = new List<StocksData>();
            List<StocksData> customerBlocking = new List<StocksData>();

            col.Blocking = new List<StocksData>();

            mortgateAmount = string.IsNullOrEmpty(txtMortgageAmount.TextBox1.Text) ? 0 :
                                        Convert.ToDecimal(txtMortgageAmount.TextBox1.Text);

            col = getCollateral(txtAccNo.Text, mortgateAmount);
            mortgateAmount -= col.Amount;
            customerBlocking = MergeStockList(customerBlocking, col.Blocking);
            customerHolding = MergeStockList(customerHolding, col.Remain);

            if (mortgateAmount > 0)
                MessageBox.Show("Không đủ chứng khoán để thực hiện");

            SendStocksUIToGrid(grvStocksBlocking, customerBlocking);
            SendStocksUIToGrid(grvStockRemain, customerHolding);
        }

        private void UpdateHolding(string accountNo)
        {
            CollateralUI col = new CollateralUI();
            List<StocksData> customerHolding = new List<StocksData>();
            List<StocksData> customerBlocking = new List<StocksData>();

            col.Blocking = new List<StocksData>();
            col = getCollateral(accountNo, 0);
            customerBlocking = MergeStockList(customerBlocking, col.Blocking);
            customerHolding = MergeStockList(customerHolding, col.Remain);
            SendStocksUIToGrid(grvStocksBlocking, customerBlocking);
            SendStocksUIToGrid(grvStockRemain, customerHolding);
        }

        private List<StocksData> MergeStockList(List<StocksData> list1, List<StocksData> list2)
        {
            List<StocksData> list = new List<StocksData>();
            list.AddRange(list1);

            int stocknum = list.Count;
            if (list.Count.Equals(0))
            {
                for (int i = 0; i < list2.Count; i++)
                    if (list2[i].Quantity >= 100)
                        list.Add(list2[i]);
            }
            else
            {
                for (int i = 0; i < list2.Count; i++)
                {
                    bool notMatch = true;

                    for (int j = 0; j < list.Count; j++)
                        if (list2[i].IsEquals(list[j]))
                        {
                            list[j].Quantity += list2[i].Quantity;
                            notMatch = false;
                        }

                    if ((list2[i].Quantity >= 100) && notMatch)
                        list.Add(list2[i]);

                }
            }
            return list;
        }

        private decimal GetBlockQttyByCodeAndAccount(string accountno, string symbol)
        {
            List<ContractData> openContracts = client.searchContract(string.Empty, string.Empty,
                                                    DateTime.Now, DateTime.Now, 0, 0,
                                                    Convert.ToInt32(ContracType.Loan),
                                                    ContractStatus.Open.ToString(), accountno, 
                                                    string.Empty);
            decimal qtty = 0;
            foreach (ContractData contract in openContracts)
            {
                List<MortgageTrans> trans = client.searchMortgageTrans(symbol, accountno, contract.ContractNo,
                                                        DateTime.Now, DateTime.Now,
                                                        Convert.ToInt32(TransType.BlockStock), 0, 0, 0, 0);
                foreach (MortgageTrans tran in trans)
                    qtty += tran.Debit;
            }
            return qtty;
        }

        private CollateralUI getCollateral(string AccountNo, decimal mortgateAmount)
        {
            CollateralUI col = new CollateralUI();
            col.Blocking = new List<StocksData>();
            col.Remain = new List<StocksData>();

            AssetUI subAssest = getAssetInfoByAccountNo(AccountNo, false, true, true);

            foreach (StocksData stock in subAssest.getStockHolding())
            {

                stock.Quantity -= GetBlockQttyByCodeAndAccount(AccountNo, stock.Symbol);

                // Check for block amount in transactions
                while ((mortgateAmount > 0) && (stock.Quantity >= 100))
                {
                    // Loan amount greater than stocks value
                    if (mortgateAmount >= stock.Value)
                    {
                        // Block cash
                        col.Blocking.Add(new StocksData(stock.Symbol, stock.Quantity, stock.Ref, stock.Name));
                        col.Amount += stock.Value;
                        // Transfer money
                        mortgateAmount -= stock.Value;
                        stock.Quantity = 0;
                    }
                    else
                    {
                        // Block stocks
                        decimal qtty = (Convert.ToInt32(Math.Ceiling(mortgateAmount /
                                                                    (stock.Ref * 1000)) / 100) + 1) * 100;

                        col.Amount += mortgateAmount;
                        stock.Quantity -= qtty;
                        StocksData temp = new StocksData(stock.Symbol, qtty, stock.Ref, stock.TillSettlement,
                                                        stock.AllowRate, stock.Name);
                        col.Blocking.Add(temp);
                        col.Amount += temp.Value;

                        // Transfer cash
                        mortgateAmount = 0;
                    }
                }
            }
            col.Remain = subAssest.getStockHolding();
            return col;
        }

        private decimal getBlockList(string AccountNo, decimal Amount)
        {
            return 0;
        }

        private decimal getPortfolioValue(List<StocksData> list, bool isDiscount)
        {
            decimal stockvalue = 0;

            DALclient client = new DALclient();
            foreach (StocksData item in list)
            {
                QuoteDataUI quote = client.getQuote(item.Symbol);
                decimal amplitude = (quote.ExCenter.Equals("HOSE")) ? 0.05m : 0.07m;

                if (isDiscount)
                    stockvalue += item.Ref * item.Quantity * item.AllowRate * 1000;
                else
                    stockvalue += item.Ref * item.Quantity * 1000;
            }

            return stockvalue;
        }

        private AssetUI getAssetInfoByAccountNo(string AccountNo, bool isDiscount, bool isCountSettlement, bool isIntraday)
        {
            AssetUI asset = new AssetUI();
            DALclient client = new DALclient();

            try
            {
                #region  Definitions
                List<TransDataUI> trans = new List<TransDataUI>();
                List<StocksData> PortfolioHolding = new List<StocksData>();
                List<BankDataUI> cash = new List<BankDataUI>();
                List<DateTime> backdate = new List<DateTime>();
                List<TradingResultUI> tr = new List<TradingResultUI>();
                List<AccountDataUI> hold = new List<AccountDataUI>();

                List<OrderUI> AllCustomerOrders = new List<OrderUI>();
                List<OrderUI> CustormerOrders = new List<OrderUI>();
                List<OrderUI> HoOrders = new List<OrderUI>();
                List<OrderUI> HaOrders = new List<OrderUI>();

                List<StocksData> T1holding = new List<StocksData>();
                List<StocksData> T2holding = new List<StocksData>();
                List<StocksData> T3holding = new List<StocksData>();


                Filter flt = new Filter();

                bool isClearing;

                #endregion

                #region  Share Objects
                decimal investorID = client.getAccountData(AccountNo).investorId;
                backdate = client.getBackDate();
                isClearing = client.isClearingDone();
                #endregion

                #region Cash
                cash = client.getBankDataByInvestorId(investorID);
                asset.PreLoan = client.getPreLoanByInvestor(investorID);
                #endregion

                #region Stocks

                #region T0

                #region Get all today orders
                HoOrders = client.getHoseOrders();
                HaOrders = client.getHastcOrders();
                AllCustomerOrders = MergeOrders(HaOrders, HoOrders);
                #endregion

                if (isClearing)
                    AllCustomerOrders = null;
                else
                    if (AllCustomerOrders.Count.Equals(0))
                        tr = client.getTradingResultHistory(
                            investorID, DateTime.Today, DateTime.Today, string.Empty, string.Empty,
                            "SELL", string.Empty, string.Empty, 0, 99999999, 0, 99999999);
                //Hiển thị danh sách lệnh của khách hàng
                CustormerOrders = flt.ordersFilter(AllCustomerOrders, AccountNo, string.Empty, string.Empty);
                asset.T0Trading = CustormerOrders;
                //Tính số tiền đã bán được
                asset.SoldAmount = flt.getNettingAmount(CustormerOrders);
                //01. Hoạch toán luôn phần tiền đã bán được vào tiền chờ về
                if (isIntraday)
                    asset.NettingAmount += asset.SoldAmount;

                foreach (OrderUI order in CustormerOrders)
                {
                    if (order.Side.Equals("MUA"))
                    {
                        QuoteDataUI quote = client.getQuote(order.Symbol);

                        //02. Giải tỏa tiền cho phần chứng khoán đã mua nhưng chưa khớp
                        //    chuyển từ phần đã phong tỏa sang giao dịch
                        if (isIntraday)
                        {
                            asset.TradingAmount += (order.Volume - order.MVolume) * quote.Ref * 1000;
                            asset.BlockAmount -= (order.Volume - order.MVolume) * quote.Ref * 1000;
                        }

                        //02. Tính lại giá trị ck mua vừa khớp với thời gian chờ về T+3
                        decimal amplitude = (quote.ExCenter.Equals("HOSE")) ? 0.05m : 0.07m;
                        if (isDiscount)
                            asset.T0BoughtStockValue += order.MVolume * estimateFutureValue(quote.Ref, amplitude, 3) * 1000;
                        else
                            asset.T0BoughtStockValue += order.MVolume * estimateFutureValue(quote.Ref, amplitude, 0) * 1000;
                    }
                }
                asset.BoughtAmount += flt.getSpentAmount(CustormerOrders);

                #endregion

                //Tra cứu danh mục đầu tư
                hold = client.getAccountByInvestorId(investorID);
                foreach (AccountDataUI stock in hold)
                {
                    long quantity = Convert.ToInt64(stock.tradingAmount);
                    QuoteDataUI quote = client.getQuote(stock.stockId);
                    MortgageMornitorDAL dal = new MortgageMornitorDAL();
                    decimal rate = dal.getLoanRate(DateTime.Today, stock.stockId);

                    if ((CustormerOrders.Count.Equals(0)) && (tr.Count > 0))
                    {
                        foreach (TradingResultUI order in tr)
                            if (order.Symbol.Equals(quote.Symbol) && order.Side.Equals("Bán"))
                            {
                                //Trước giờ giao dịch (chưa có danh sách lệnh trả về từ TTGD) nếu đặt lệnh bán
                                //Tất cả lệnh bán coi như sẽ không khớp và chuyển chuyển trả lại phần CK đó vào số dư giao dịch
                                quantity += Convert.ToInt64(order.RootOrder.quantity);
                            }
                    }
                    else
                    {
                        //01. Chuyển phần chứng khoán bán nhưng chưa khớp vào số dư giao dịch
                        if (isIntraday)
                            quantity += flt.getSellQttyBySymbol(CustormerOrders,
                                                              AccountNo, quote.Symbol);
                        else
                            quantity += flt.getRemainSellQttyBySymbol(CustormerOrders,
                                                                  AccountNo, quote.Symbol);
                    }
                    PortfolioHolding.Add(new StocksData(quote.Symbol, quantity, quote.Ref, 0, rate, quote.CompanyName));
                }
                asset.T0 = PortfolioHolding;
                asset.PorfolioTradingStockValue = getPortfolioValue(PortfolioHolding, isDiscount);

                //Tra cứu thông tin thanh toán bù trừ


                if (!isClearing)
                {
                    T1holding = ConvertToStocksUI(client.getStockNettingInvestorId(
                                                        investorID, backdate[1]), 3, isCountSettlement);
                    T2holding = ConvertToStocksUI(client.getStockNettingInvestorId(
                                                        investorID, backdate[2]), 2, isCountSettlement);
                    T3holding = ConvertToStocksUI(client.getStockNettingInvestorId(
                                                        investorID, backdate[3]), 1, isCountSettlement);
                }
                else
                {
                    T1holding = ConvertToStocksUI(client.getStockNettingInvestorId(
                                                        investorID, backdate[0]), 3, isCountSettlement);
                    T2holding = ConvertToStocksUI(client.getStockNettingInvestorId(
                                                        investorID, backdate[1]), 2, isCountSettlement);
                    T3holding = ConvertToStocksUI(client.getStockNettingInvestorId(
                                                        investorID, backdate[2]), 1, isCountSettlement);

                }

                asset.T1BoughtStockValue = getPortfolioValue(T1holding, isDiscount);
                asset.T1 = T1holding;
                asset.T2BoughtStockValue = getPortfolioValue(T2holding, isDiscount);
                asset.T2 = T2holding;
                asset.T3BoughtStockValue = getPortfolioValue(T3holding, isDiscount);
                asset.T3 = T3holding;


                #endregion

                asset.StockAmount += asset.PorfolioTradingStockValue
                                    + asset.T0BoughtStockValue
                                    + asset.T1BoughtStockValue
                                    + asset.T2BoughtStockValue
                                    + asset.T3BoughtStockValue;
                asset.TradingAmount += cash[0].tradingAmount;
                asset.NettingAmount += cash[0].nettingAmount + asset.SoldAmount;
                asset.BlockAmount += cash[0].blockAmount;
                asset.CashAmount = asset.NettingAmount + cash[0].tradingAmount - asset.PreLoan;
                asset.AssetAmount = asset.StockAmount +
                                    asset.NettingAmount +
                                    asset.TradingAmount -
                                    asset.PreLoan;

                return asset;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return asset;
            }
        }

        private List<StocksData> ConvertToStocksUI(List<TradingResultUI> list, int T, bool isCountSettlement)
        {
            List<StocksData> holding = new List<StocksData>();
            DALclient client = new DALclient();
            MortgageMornitorDAL dal = new MortgageMornitorDAL();
            decimal amplitude = 0;
            foreach (TradingResultUI result in list)
            {
                QuoteDataUI quote = client.getQuote(result.Symbol);

                if (quote != null)
                {
                    decimal rate = dal.getLoanRate(DateTime.Today, result.Symbol);
                    decimal refPrice = quote.Ref;
                    if (isCountSettlement)
                    {
                        amplitude = (quote.ExCenter.Equals("HOSE")) ? 0.05m : 0.07m;
                        refPrice = estimateFutureValue(quote.Ref, amplitude, T);
                    }
                    holding.Add(new StocksData(quote.Symbol, result.SubQtty, refPrice, T, rate, quote.CompanyName));

                }
            }
            return holding;
        }

        private decimal estimateFutureValue(decimal Value, decimal amplitide, int T)
        {
            decimal price = Value;
            for (int i = 0; i < T; i++)
            {
                price = price * (1 - amplitide);
            }
            return price;
        }

        private List<OrderUI> MergeOrders(List<OrderUI> orders1, List<OrderUI> orders2)
        {
            try
            {
                List<OrderUI> mergedlist = new List<OrderUI>();
                mergedlist.AddRange(orders1);
                mergedlist.AddRange(orders2);
                return mergedlist;
            }
            catch (System.Exception e)
            {
                throw e;
            }
        }

        private void frmMortgage_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtContractNo.Text))
                btnCreate.Enabled = false;
            else
                btnCreate.Enabled = true;
        }

        private void btnFindCustomer()
        {
            //Find in the local database
            AccountData customer = client.getCustomerByID(txtIDCardNo.Text);
            UpdateCustomerInfo(customer);
            UpdateFee();

            //Find in BOSC database

            //Update fee information

            //Create new
            if (customer == null)
                MessageBox.Show("Chưa có thông tin về khách hàng này.", "Oops!");
        }

        private void UpdateFee()
        {
            txtFee.Text = getFee(0, txtIDCardNo.Text, txtContractNo.Text, txtAccountNo.Text).ToString("N3");
            txtPenaltyFee.Text = getFee(1, txtIDCardNo.Text, txtContractNo.Text, txtAccountNo.Text).ToString("N3");
            txtProcessFee.Text = getFee(2, txtIDCardNo.Text, txtContractNo.Text, txtAccountNo.Text).ToString("N0");
        }

        private decimal getFee(int type, string investorid, string contractno, string accountno)
        {
            FeeData item = client.getFeeByType(type, investorid, contractno, accountno);

            if (item == null)
            {
                FeeData std = client.getFeeByType(type, string.Empty, string.Empty, string.Empty);
                if (std != null)
                    return std.FeeValue;
                else
                    return 0;
            }
            else
                return item.FeeValue;
        }

        private void UpdateCustomerInfo(AccountData customer)
        {
            if (customer != null)
            {
                txtName.Text = customer.Name;
                txtIDCardNo.Text = customer.IDcardNo;
                dtIdCardDate.Value = customer.IDcardDate;
                txtAccountNo.Text = customer.AccountNo;
                txtPhone.Text = customer.PhoneMobile;

                List<string> accounts = client.getCustomerAccounts(customer.IDcardNo);
                decimal accumlateLoan = 0;
                lstAccountNo.Items.Clear();
                foreach (string acc in accounts)
                {
                    lstAccountNo.Items.Add(acc);
                    accumlateLoan += getAccumulateValueByAccountNo(acc);
                }
                txtAccumulateLoan.Text = accumlateLoan.ToString("N0");

                string AccountNo = (string.IsNullOrEmpty(txtAccNo.Text)) ?
                                lstAccountNo.Items[0].ToString() : txtAccNo.Text;
                txtAccNo.Text = AccountNo;
                UpdateAccountInfo(AccountNo);
                txtAccumlateValue.Text = getAccumulateValueByAccountNo(AccountNo).ToString("N0");
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtMortgageAmount_Leave(object sender, EventArgs e)
        {
            UpdateFeeValue();
        }

        private void UpdateFeeValue()
        {
            //             decimal amount = 0;
            //             decimal fee = 0;
            //             decimal penaltyfee = 0;
            //             decimal processfee = 0;

            //             if (decimal.TryParse(txtMortgageAmount.TextBox1.Text, out amount))
            //             {
            //                 if (decimal.TryParse(txtFee.Text, out fee))
            //                     lblFee.Text = (amount * fee).ToString("N0");
            //                 else
            //                     lblFee.Text = string.Empty;
            // 
            //                 if (decimal.TryParse(txtPenaltyFee.Text, out penaltyfee))
            //                     lblPenaltyFee.Text = (amount * penaltyfee).ToString("N0");
            //                 else
            //                     lblPenaltyFee.Text = string.Empty;
            // 
            //                 if (decimal.TryParse(txtProcessFee.Text, out processfee))
            //                     lblProcessFee.Text = processfee.ToString("N0");
            //                 else
            //                     lblProcessFee.Text = string.Empty;
            //             }
        }

        private void SendStocksUIToGrid(DataGridView grv, List<StocksData> holding)
        {
            grv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            grv.RowHeadersVisible = false;
            grv.DataSource = holding;

            if (holding.Count > 0)
            {
                grv.Columns["Symbol"].DisplayIndex = 0;
                grv.Columns["Quantity"].DisplayIndex = 1;
                grv.Columns["Quantity"].DefaultCellStyle.Format = "N0";
                grv.Columns["Ref"].DisplayIndex = 2;
                grv.Columns["Ref"].DefaultCellStyle.Format = "N2";

                grv.Columns["Value"].DisplayIndex = 3;
                grv.Columns["Value"].DefaultCellStyle.Format = "N0";


                grv.Columns["Symbol"].HeaderText = "MCK";
                grv.Columns["Quantity"].HeaderText = "KL";
                grv.Columns["Ref"].HeaderText = "Giá";
                grv.Columns["Value"].HeaderText = "G.trị";
                grv.Columns["Name"].HeaderText = "Cty";
                grv.Columns["TillSettlement"].HeaderText = "Ng.về";
                grv.Columns["AllowRate"].HeaderText = "T.lệ";

                grv.Columns["Quantity"].DefaultCellStyle.Format = "N0";
                grv.Columns["Value"].DefaultCellStyle.Format = "N0";
                grv.Columns["Name"].Visible = false;
            }
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            CollateralUI col = new CollateralUI();
            List<StocksData> customerHolding = new List<StocksData>();
            List<StocksData> customerBlocking = new List<StocksData>();

            string ContractNo = "P_" + DateTime.Now.ToString("yyMMdd_")
                                    + txtAccNo.Text.Substring(4, txtAccNo.Text.Length - 4)
                                    + DateTime.Now.ToString("hhmmss");

            txtContractNo.Text = ContractNo;
            decimal mortgateAmount = Convert.ToDecimal(txtMortgageAmount.TextBox1.Text);
            // Insert new contract
            string contractID = client.InsertContract(ContractNo, txtIDCardNo.Text,
                                            dtFrom.Value, dtTo.Value,
                                            Convert.ToDecimal(txtFee.Text),
                                            Convert.ToDecimal(txtPenaltyFee.Text),
                                            Convert.ToDecimal(txtProcessFee.Text),
                                            Convert.ToInt32(ContracType.Loan),
                                            ContractStatus.Open.ToString(),
                                            mortgateAmount, txtAccNo.Text, ContractNo);

            col = getCollateral(txtAccNo.Text, mortgateAmount);
            customerBlocking = MergeStockList(customerBlocking, col.Blocking);
            customerHolding = MergeStockList(customerHolding, col.Remain);

            if ((col.Amount - mortgateAmount) > 0)
            {
                foreach (StocksData item in customerBlocking)
                    client.InsertMortgageTrans(txtAccNo.Text,
                                                contractID, DateTime.Now, item.Symbol,
                                                Convert.ToInt32(TransType.BlockStock),
                                                0, item.Quantity);
                // Update cash transaction
                client.InsertMortgageTrans(txtAccNo.Text,
                                            contractID, DateTime.Now, contractID,
                                            Convert.ToInt32(TransType.WithDrawCash),
                                            mortgateAmount, 0);

                SendStocksUIToGrid(grvStocksBlocking, customerBlocking);
                SendStocksUIToGrid(grvStockRemain, customerHolding);
                MessageBox.Show("Contract: " + contractID + " created successfully!");

                ResetUI();
            }
            else
            {
                MessageBox.Show("Not enough cash. Contract has not been created.");
                return;
            }
        }

        private void ResetUI()
        {
            txtMortgageAmount.TextBox1.Text = string.Empty;
            dtFrom.Value = DateTime.Now;
            dtTo.Value = DateTime.Now;
            txtContractNo.Text = "P_" + DateTime.Now.ToString("yyMMdd_")
                                    + txtAccNo.Text.Substring(4, txtAccNo.Text.Length - 4)
                                    + DateTime.Now.ToString("hhmmss");
            txtAccumlateValue.Text = getAccumulateValueByAccountNo(txtAccNo.Text).ToString("N0");
            decimal accumlateLoan = 0;

            List<string> accounts = client.getCustomerAccounts(txtIDCardNo.Text);
            lstAccountNo.Items.Clear();
            foreach (string acc in accounts)
            {
                lstAccountNo.Items.Add(acc);
                accumlateLoan += getAccumulateValueByAccountNo(acc);
            }
            txtAccumulateLoan.Text = accumlateLoan.ToString("N0");
        }

        private void lstAccountNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtAccNo.Text = lstAccountNo.SelectedItem.ToString();
        }

        private void txtIDCardNo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue.Equals(13))
                btnFindCustomer();
        }

        private decimal getAccumulateValueByAccountNo(string AccountNo)
        {
            decimal AccumulateValue = 0;
            List<ContractData> cts = client.searchContract(string.Empty,
                                client.getCustomerIDByAccountNo(AccountNo),
                                DateTime.Today, DateTime.Today, 0, 0,
                                Convert.ToInt32(ContracType.Loan), ContractStatus.Open.ToString(),
                                AccountNo, string.Empty);

            foreach (ContractData ct in cts)
            {
                List<MortgageTrans> trans = client.getMortgageTransByCode(ct.ContractNo);
                foreach (MortgageTrans tran in trans)
                    if (tran.TransType.Equals(Convert.ToInt32(TransType.WithDrawCash)))
                        AccumulateValue += tran.Credit;
                    else
                        AccumulateValue -= tran.Debit;
            }

            return AccumulateValue;
        }

        private void txtContractNo_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtContractNo.Text))
                btnCreate.Enabled = false;
            else
                btnCreate.Enabled = true;
        }

        private void UpdateAccountInfo(string AccountNo)
        {
            AccountData acc = history.getCustomerInfo(AccountNo);
            if (acc != null)
            {
                txtAccName.Text = acc.Name;
                txtAccIdCardNo.Text = acc.IDcardNo;
                txtAccIdCardIssuer.Text = acc.IDcardIssuer;
                txtAccIdCardDate.Text = acc.IDcardDate.ToString("yyyy/MM/dd");
                txtAccIdCardIssuer.Text = acc.IDcardIssuer;
                txtAccMobile.Text = acc.PhoneMobile;
                txtAccFix.Text = acc.PhoneFix;
                txtAccContact.Text = acc.AddressContact;
                txtAccResident.Text = acc.AddressResident;
                txtAccEmail.Text = acc.Email;
                rdAccIsMale.Checked = (acc.Gender.Equals("Nam")) ? true : false;
            }
            else
            {
                MessageBox.Show("Account not found!");
            }
        }

        private void txtAccNo_TextChanged(object sender, EventArgs e)
        {
            txtContractNo.Text = "P_" + DateTime.Now.ToString("yyMMdd_")
                        + txtAccNo.Text.Substring(4, txtAccNo.Text.Length - 4)
                        + DateTime.Now.ToString("hhmmss");
            UpdateAccountInfo(txtAccNo.Text);
            txtAccumlateValue.Text = getAccumulateValueByAccountNo(txtAccNo.Text).ToString("N0");
            //UpdateHolding(txtAccNo.Text);
        }
    }
}
